package com.mouse.magent.proxy.handler;

import com.mouse.magent.common.handler.BaseHandler;
import com.mouse.magent.common.protocol.Command;
import com.mouse.magent.common.protocol.Header;
import com.mouse.magent.common.protocol.Message;
import com.mouse.magent.common.util.JsonUtil;
import com.mouse.magent.common.util.NettyUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ProxyClientHandler extends BaseHandler {
    private String secret;
    private Integer port;

    public ProxyClientHandler(String secret, Integer port) {
        this.secret = secret;
        this.port = port;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("secret", secret);
        resultMap.put("port", port);

        Message message = new Message();
        message.setType(Command.PROXY_CONNECT);
        Header header = new Header();
        header.setResult(JsonUtil.toJson(resultMap));
        message.setHeader(header);
        ctx.writeAndFlush(message);
        super.channelActive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                log.info("ip:{} Read idle loss connection.", NettyUtil.getRemoteIp(ctx));
                ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                Message natxMessage = new Message();
                natxMessage.setType(Command.KEEP_ALIVE);
                ctx.writeAndFlush(natxMessage);
            }
        }
    }
}
